﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using He.Common;
using System.Xml.Serialization;
using System.IO;

namespace He.API.WeiXin
{
    public class ObjectConvert
    {
        /// <summary>
        /// 将回复的对象序列化
        /// </summary>
        /// <param name="Obj"></param>
        /// <returns></returns>
        public static string ObjectToXmlSerializer(Object Obj)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            //去除xml声明
            settings.OmitXmlDeclaration = true;
            settings.Encoding = Encoding.Default;
            System.IO.MemoryStream mem = new MemoryStream();
            using (XmlWriter writer = XmlWriter.Create(mem, settings))
            {
                //去除默认命名空间xmlns:xsd和xmlns:xsi
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                XmlSerializer formatter = new XmlSerializer(Obj.GetType());
                formatter.Serialize(writer, Obj, ns);
            }
            return Encoding.Default.GetString(mem.ToArray());
        }

        /// <summary>
        /// 将回复的对象序列化
        /// </summary>
        /// <param name="responseXml"></param>
        /// <returns></returns>
        public static string ResponseXmlStr(xml responseXml)
        {
            return ESBasic.XmlSerializeObject(responseXml);
        }

        /// <summary>   
        /// XML转化为Model的方法   
        /// </summary>   
        /// <param name="xml">要转化的XML</param>  
        /// <param name="SampleModel">Model的实体示例，New一个出来即可</param>  
        /// <returns></returns>   
        public static xml XMLToModel(string xml, xml model)
        {
            if (string.IsNullOrEmpty(xml))
                return null;
            else
            {
                XmlDocument xmldoc = XmlHelper.LoadXml(xml);

                XmlNodeList attributes = xmldoc.SelectSingleNode("xml").ChildNodes;
                foreach (XmlNode node in attributes)
                {
                    foreach (PropertyInfo property in model.GetType().GetProperties())
                    {
                        if (node.Name == property.Name)
                        {
                            if (property.PropertyType == typeof(System.Guid))
                            {
                                property.SetValue(model, new Guid(node.InnerText), null);
                            }
                            else
                            {
                                property.SetValue(model, Convert.ChangeType(node.InnerText, property.PropertyType), null);
                            }
                        }
                    }
                }
                return model;
            }
        }

        /// <summary>   
        /// Model转化为XML的方法   
        /// </summary>   
        /// <param name="model">要转化的Model</param>  
        /// <returns></returns>   
        public static string ModelToXML(object model)
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlElement ModelNode = xmldoc.CreateElement("xml");
            xmldoc.AppendChild(ModelNode);

            if (model != null)
            {
                foreach (PropertyInfo property in model.GetType().GetProperties())
                {
                    if (property.GetValue(model, null) != null)
                    {
                        XmlElement attribute = xmldoc.CreateElement(property.Name);
                        attribute.InnerText = string.Format("![CDATA[{0}]]", property.GetValue(model, null).ToString());
                        ModelNode.AppendChild(attribute);
                    }
                }
            }
            return xmldoc.OuterXml;
        }

        /// <summary>
        /// 根据节点属性封装XML字符串
        /// </summary>
        /// <param name="Nodes"></param>
        /// <returns></returns>
        public static string ModelToXmlStr(xml Nodes)
        {
            Type t = Nodes.GetType();

            StringBuilder strTemp = new StringBuilder();
            strTemp.Append("<xml>");
            //遍历所有属性
            foreach (PropertyInfo pi in t.GetProperties())
            {
                string name = pi.Name;
                object value = pi.GetValue(Nodes, null);
                //只追加不为空的结点
                if (value != null)
                {
                    strTemp.AppendFormat("<{0}><![CDATA[{1}]]></{0}>", name, value);
                }
            }
            strTemp.Append("</xml>");
            return strTemp.ToString();
        }

        /// <summary>
        /// 将指定时间转换为整形格式的时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int DateTimeToInt(DateTime time)
        {
            DateTime time2 = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1));
            TimeSpan span = (TimeSpan)(time - time2);
            return (int)span.TotalSeconds;
        }

        #region 暂不使用
        /// <summary>
        /// 接收微信服务器发送的XML
        /// </summary>
        /// <returns></returns>
        public static xml GetRequestXml2()
        {
            string strXml = InputHelper.GetInpugStream();
            if (!string.IsNullOrEmpty(strXml))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strXml);
                if (doc != null)
                {
                    XmlElement element = doc.DocumentElement;

                    xml requestXmL = new xml
                    {
                        ToUserName = element.SelectSingleNode(Enums.XmlNode.ToUserName.ToString()).InnerText,
                        FromUserName = element.SelectSingleNode(Enums.XmlNode.FromUserName.ToString()).InnerText,
                        CreateTime = element.SelectSingleNode(Enums.XmlNode.CreateTime.ToString()).InnerText,
                        MsgType = element.SelectSingleNode(Enums.XmlNode.MsgType.ToString()).InnerText,
                    };
                    //文本
                    if (requestXmL.MsgType == Enums.MsgType.text.ToString())
                    {
                        requestXmL.Content = element.SelectSingleNode(Enums.XmlNode.Content.ToString()).InnerText;
                    }
                    //位置
                    else if (requestXmL.MsgType == Enums.MsgType.location.ToString())
                    {
                        requestXmL.Location_X = element.SelectSingleNode(Enums.XmlNode.Location_X.ToString()).InnerText;
                        requestXmL.Location_Y = element.SelectSingleNode(Enums.XmlNode.Location_Y.ToString()).InnerText;
                        requestXmL.Scale = element.SelectSingleNode(Enums.XmlNode.Scale.ToString()).InnerText;
                        requestXmL.Label = element.SelectSingleNode(Enums.XmlNode.Label.ToString()).InnerText;
                    }
                    //图片
                    else if (requestXmL.MsgType == Enums.MsgType.image.ToString())
                    {
                        requestXmL.PicUrl = element.SelectSingleNode(Enums.XmlNode.PicUrl.ToString()).InnerText;
                    }
                    //推送事件
                    else if (requestXmL.MsgType == Enums.MsgType.Event.ToString().ToLower())
                    {
                        requestXmL.Event = element.SelectSingleNode(Enums.XmlNode.Event.ToString()).InnerText;
                    }
                    return requestXmL;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        #endregion
    }
}
